;; (defun java-print()
;;   (interactive)
;;   (insert "System.out.println("");")
;;   )

(defun java-main()
  (interactive)
  (setq file-name (file-name-nondirectory buffer-file-name))
  (setq begin (string-match "\\.[^.]*\\'" file-name))
  (setq file-name-without-extended (substring file-name 0 begin))
  (insert (format "public class %s {
    public static void main(String[] args) {
        
    }
}" file-name-without-extended))
  )

(defun java-commandline()
  "java command line"
  (interactive)
  (insert "java -cp .:sqlitejdbc-v056.jar Test
java -cp .:sqlitejdbc-v056.jar org.test.test.Test
")
  )


(defun java-jbutton()
  (interactive)
  (insert "import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class test {
    public static void main(String[] args) {
        JFrame frame1 = new JFrame(\"JAVA\");
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        JButton button = new JButton(\" >> Test <<\");
        //Add action listener to button
        button.addActionListener(new ActionListener() {
 
                public void actionPerformed(ActionEvent e)
                {
                    //Execute when button is pressed
                    System.out.println(\"You clicked the button\");
                }
            });      
 
        frame1.getContentPane().add(button);
        frame1.pack();
        frame1.setVisible(true);
    }
}")
  )

(defun java-scanf()
  (interactive)
  (insert "    public static void main(String[] args) throws IOException {  
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String string;  
        do{  
            string=br.readLine();  
            System.out.println(string);  
        }while(!string.equals(\"stop\"));  
    }  ")
  )

(defun java-reflection-getField()
  (interactive)
  (insert "GetSetFieldDemo demo = new GetSetFieldDemo();
Class clazz = demo.getClass();
 
try {
    //
    // Get field id, set it value and read it back
    //
    Field field = clazz.getField(\"id\");
    field.set(demo, new Long(10));
    Object value = field.get(demo);
    System.out.println(\"Value = \" + value);
 
    //
    // Get static field date, set it value and read it back
    //
    field = clazz.getField(\"now\");
    field.set(null, new Date());
    value = field.get(null);
    System.out.println(\"Value = \" + value);

    Field[] fields = clazz.getFields();

    for(int i = 0;i<fields.length;i++) {
        System.out.println(fields[i].getName());
    }

    Method[] methods = clazz.getMethods();

    for(int i = 0;i<methods.length;i++){
        System.out.println(methods[i].getName());
    }
            
} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}")
  )

(defun java-reflection-method()
  (interactive)
  (insert "try {
    Class c = Class.forName(\"JavaReflection\");
    Method m[] = c.getDeclaredMethods();
			
    for(int i=0;i<m.length;i++)
        {
            System.out.println(m[i].toString());
        }
} catch (Exception e) {
    // TODO: handle exception
}")
  )

(defun java-jframe()
  (interactive)
  (insert "JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

class SketchFrame extends JFrame
{
    public SketchFrame()
    {
        setTitle(\"Sketch\");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

        // add panel to frame

        SketchPanel panel = new SketchPanel();
        add(panel);
    }

    public static final int DEFAULT_WIDTH = 300;
    public static final int DEFAULT_HEIGHT = 200;
}

")
  )

(defun java-debugbreak()
  (interactive)
  (insert "
com.sun.jdi.connect.AttachingConnector

-Xdebug -Xrunjdwp:transport=dt_socket,address=9999,server=y,suspend=n,onthrow=com.whatever.TurnOnDebuggerException,launch=nothing

//Java Code to turn on debugger:

try {
    throw new TurnOnDebuggerException();
} catch (TurnOnDebugger td) {
   //Nothing
}
")
  )


(defun java-safePrintln()
  (interactive)
  (insert "public void safePrintln(String s) {
  synchronized (System.out) {
    System.out.println(s);
  }
}")
  )

(defun eclipse-project()
  (interactive)
  (insert "
open eclipse
File > Import and select General > Existing Projects

click 'finish' to finish
")
  )

(defun eclipse-svn()
  (interactive)
  (insert "
* How to install subversion

eclipse->Help->Install New Software...
put the follow url 'http://subclipse.tigris.org/update_1.6.x'
'http://subclipse.tigris.org/update_1.8.x'
")
  )

(defun eclipse-uml()
  ""
  (interactive)
  (insert "eclipse objectaid
")
  )

(defun eclipse-autocomplete()
  (interactive)
  (insert "Windows->Preferences->Java->Editor->Content Asist,Auto activation triggers for Java

put '.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
")
  )


(defun java-properties()
  "read java properties "
  (interactive)
  (insert "package org.apache.tomcat;

import java.io.InputStream;
import java.util.Properties;

public class Apr {
    private static String aprInfo = null;

    static {

        try {
            InputStream is = Apr.class.getResourceAsStream
                (\"/org/apache/tomcat/apr.properties\");
            Properties props = new Properties();
            props.load(is);
            is.close();
            aprInfo = props.getProperty(\"tcn.info\");
        }
        catch (Throwable t) {
            ; // Nothing
        }
    }
}

//apr.properties content
//tcn.info=Tomcat Native/@VERSION@
")
  )

(defun java-time()
  "calc java function time"
  (interactive)
  (insert "public class Test { 
         public static void main(String[] args) {
                   double start  = System.currentTimeMillis() ; 
                           for( int i = 0 ; i < 100000  ; i ++){
                                   System.out.println("") ; 
                          }
           double end = System.currentTimeMillis() ; 
           System.out.println(\"time is : \" + (end - start)); 
  
 }
}")
  )

(defun java-thread-runnable()
  ""
  (interactive)
  (insert "")
  )

(defun java-loghelper()
  "print class name, line number, method name"
  (interactive)
  (insert "public final class LogHelper {  
    private static boolean mIsDebugMode = true;
    private static String mLogTag = \"LogHelper\";  
  
    private static final String CLASS_METHOD_LINE_FORMAT = \"%s.%s()  Line:%d  (%s)\";  
  
    public static void trace() {  
        if (mIsDebugMode) {  
            StackTraceElement traceElement = Thread.currentThread()  
                    .getStackTrace()[3]; // 3 may not correct, 1 may be good.
            String logText = String.format(CLASS_METHOD_LINE_FORMAT,  
                    traceElement.getClassName(), traceElement.getMethodName(),  
                    traceElement.getLineNumber(), traceElement.getFileName());  
            Log.d(mLogTag, logText);
        }  
    }  
}  ")
  )

(defun java-print()
  (interactive)
  (beginning-of-buffer)
  ;; (setq words (match-string 1))
  (while (re-search-forward ")
	{" nil t)
    (replace-match ")
	{
            System.out.println(this.getClass().getSimpleName() + \" \" +Thread.currentThread().getStackTrace()[1].getMethodName());")
    )
  )

(defun java-printToFile()
  ""
  (interactive)
  (insert "")
  )

(defun java-log()
  ""
  (interactive)
  (insert "package com.vogella.logger;



import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.logging.Formatter;

import java.util.logging.Handler;

import java.util.logging.Level;

import java.util.logging.LogRecord;



// this custom formatter formats parts of a log record to a single line

class MyHtmlFormatter extends Formatter {

  // this method is called for every log records

  public String format(LogRecord rec) {

    StringBuffer buf = new StringBuffer(1000);

    buf.append(\"<tr>\\n\");



    // colorize any levels >= WARNING in red

    if (rec.getLevel().intValue() >= Level.WARNING.intValue()) {

      buf.append(\"\\t<td style=\\\"color:red\\\">\");

      buf.append(\"<b>\");

      buf.append(rec.getLevel());

      buf.append(\"</b>\");

    } else {

      buf.append(\"\\t<td>\");

      buf.append(rec.getLevel());

    }



    buf.append(\"</td>\\n\");

    buf.append(\"\\t<td>\");

    buf.append(calcDate(rec.getMillis()));

    buf.append(\"</td>\\n\");

    buf.append(\"\\t<td>\");

    buf.append(formatMessage(rec));

    buf.append(\"</td>\\n\");

    buf.append(\"</tr>\\n\");



    return buf.toString();

  }



  private String calcDate(long millisecs) {

    SimpleDateFormat date_format = new SimpleDateFormat(\"MMM dd,yyyy HH:mm\");

    Date resultdate = new Date(millisecs);

    return date_format.format(resultdate);

  }



  // this method is called just after the handler using this

  // formatter is created

  public String getHead(Handler h) {

    return \"<!DOCTYPE html>\\n<head>\\n<style\"

        + \"type=\\\"text/css\\\">\\n\"

        + \"table { width: 100% }\\n\"

        + \"th { font:bold 10pt Tahoma; }\\n\"

        + \"td { font:normal 10pt Tahoma; }\\n\"

        + \"h1 {font:normal 11pt Tahoma;}\\n\"

        + \"</style>\\n\"

        + \"</head>\\n\"

        + \"<body>\\n\"

        + \"<h1>\" + (new Date()) + \"</h1>\\n\"+

        + \"<table border=\\\"0\\\" cellpadding=\\\"5\\\" cellspacing=\\\"3\\\">\\n\"

        + \"<tr align=\\\"left\\\">\\n\"

        + \"\\t<th style=\\\"width:10%\\\">Loglevel</th>\\n\"

        + \"\\t<th style=\\\"width:15%\\\">Time</th>\\n\"

        + \"\\t<th style=\\\"width:75%\\\">Log Message</th>\\n\"

        + \"</tr>\\n\";

  }



  // this method is called just after the handler using this

  // formatter is closed

  public String getTail(Handler h) {

    return \"</table>\\n</body>\\n</html>\";

  }

} ")
  )

(defun java-currentdir()
  ""
  (interactive)
  (insert "    	System.out.println(\"Working Directory = \" +
                System.getProperty(\"user.dir\"));")
  )

(defun java-file-to-string()
  ""
  (interactive)
  (insert "import java.util.*;
import java.io.*;

/*
 *
 */
public class Test {
    public static void main(String[] args) {
        try {
            String content = new Scanner(new File(\"Test.java\")).useDelimiter(\"\\\\Z\").next();
            System.out.println(content);
        } catch (FileNotFoundException ex) {
            System.out.println(\"File Not Found\");
        }

    }
}
")
  )

(defun java-file-to-string2()
  ""
  (interactive)
  (insert "import java.nio.charset.*;
import java.io.*;
import java.nio.file.*;
import java.util.*;

public class ReadFileTest {
    public static String readFile(String path, Charset encoding) throws IOException 
    {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }
    
    public static void main(String[] args) throws IOException {
        String s = readFile(\"ReadFileTest.java\",Charset.defaultCharset());

        System.out.println(s);

        
    }
}")
  )

(defun java-freopen()
  "java acm things"
  (interactive)
  (insert "public class Main {
    static private final String INPUT = \"C:/input.txt\";
    static private final String OUTPUT = \"C:/output.txt\";
 
    public static void main(String args[]) {
        // open I/O files
        FileInputStream instream = null;
        PrintStream outstream = null;
    
        try {
            instream = new FileInputStream(INPUT);
            outstream = new PrintStream(new FileOutputStream(OUTPUT));
            System.setIn(instream);
            System.setOut(outstream);
        } catch (Exception e) {
            System.err.println(\"Error Occurred.\");
        }
    
        Scanner in = new Scanner(System.in);
        for (;in.hasNext();) {
            int x = in.nextInt();
            System.out.println(x);
        }
    
        System.err.println(\"done.\");
        return;
    }
 
}")
  )

(defun flash-print()
  "Flash ActionScript print its own name"
  (interactive)
  (insert "private function getFunctionName(e:Error):String {
    var stackTrace:String = e.getStackTrace();     // entire stack trace
    var startIndex:int = stackTrace.indexOf(\"at \");// start of first line
    var endIndex:int = stackTrace.indexOf(\"()\");   // end of function name
    return stackTrace.substring(startIndex + 3, endIndex);
}

private function on_applicationComplete(event:FlexEvent):void {
    trace(getFunctionName(new Error());
}")
  )

(defun java-print-to-file()
  ""
  (interactive)
  (insert "        try{
            File file = new File(\"test.txt\");  
            FileOutputStream fis = new FileOutputStream(file);  
            PrintStream out = new PrintStream(fis);  
            System.setOut(out);  
            System.out.println(\"First Line\");  
            System.out.println(\"Second Line\");  
            System.out.println(\"Third Line\");  
            System.out.println(\"Fourth Line\");
        }
        catch(FileNotFoundException ex1) {
        }
")
  )

(defun java-cmd-read()
  "read command output"
  (interactive)
  (insert "public static String cmdExec(String cmdLine) {
    String line;
    String output = \"\";
    try {
        Process p = Runtime.getRuntime().exec(cmdLine);
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = input.readLine()) != null) {
            output += (line + '\\n');
        }            
        input.close();           
        }
    catch (Exception ex) {
        ex.printStackTrace();
    }

    return output;
}")
  )

(defun java-acm-template()
  "java acm template"
  (interactive)
  (insert "import java.lang.*;
import java.util.*;
import java.io.*;

public class main {
    public static void main(String[] args) {

        FileInputStream instream = null;
        PrintStream outstream = null;
        
        try{
            instream = new FileInputStream(\"1.txt\");
            outstream = new PrintStream(\"1.out\");
            System.setIn(instream);
            System.setOut(outstream);
        }
        catch(Exception e){
            System.err.println(\"Error Occurred\");
        }

        Scanner in = new Scanner(System.in);
        int T = in.nextInt();

        for(;in.hasNext();){
            for(int j=0;j<T;j++){
                System.out.println(in.nextInt() + \" \" + in.nextInt());
            }
        }

        String[] strings = { \" Hello \", \" This \", \"is \", \"Sorting \", \"Example\" };
        Arrays.sort(strings);

        for(int j=0;j<strings.length;j++)
        System.out.println(strings[j]);

        System.err.println(\"done.\");
        return;
    }
}
")
  )


(defun java-exec()
  ""
  (interactive)
  (insert "import java.io.*;
import java.lang.*;
import java.util.*;
public class main {
    
    public static void main(String[] args) {
        String s = null;
        String shutdown = \"shutdown -h now\"; 
        try {
            Process p = Runtime.getRuntime().exec(shutdown);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
 
            BufferedReader stdError = new BufferedReader(new
                 InputStreamReader(p.getErrorStream()));
 
            // read the output from the command
            System.out.println(\"Here is the standard output of the command:\\n\");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
             
            // read any errors from the attempted command
            System.out.println(\"Here is the standard error of the command (if any):\\n\");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
             
            System.exit(0);
        }
        catch (IOException e) {
            System.out.println(\"exception happened - here's what I know: \");
            e.printStackTrace();
            System.exit(-1);
        }
    }
}")
  )

